<template>
<!-- 我的钱包 -->
  <div class='myPurse'>
    <el-card class="balance mb20">
      <span class="balance-monry el-blue">{{ $store.state.user.vip | agentVipLeval }}</span>
      <!-- <img :src="vipLogo" alt="" class='vip_logo'> -->
      <i :class="vipLogoClass"></i>
      <el-popover
        placement="right"
        title="当前会员等级权益"
        width="300"
        trigger="hover"
        v-if="$store.state.user.vip != 0"
        >
        <div class='vip_Introduction'>
          <ul>
            <li><span>1，案件即时结算。</span></li>
            <li><span>2，推荐新代理人完成案件，可获得奖励。</span></li>
            <li><span>3，会员成为导师后可带徒弟，徒弟案件结算费用的50%作为指导费。</span></li>
          </ul>
        </div>
        <i slot="reference" class='el-icon-info orange ml10'></i>
      </el-popover>
      <el-button type="primary"  @click='buyVip' class='balance-btn'>{{ $store.state.user.vip == 1 ? '续费VIP' : '升级VIP' }}</el-button>
      <el-popover
        placement="right"
        title="升级成VIP后将享受以下权益"
        width="300"
        trigger="hover"
        v-if="$store.state.user.vip == 0"
        >
        <div class='vip_Introduction'>
          <ul>
            <li><span>1，案件即时结算。</span></li>
            <li><span>2，推荐新代理人完成案件，可获得奖励。</span></li>
            <li><span>3，会员成为导师后可带徒弟，徒弟案件结算费用的50%作为指导费。</span></li>
          </ul>
        </div>
        <i slot="reference" class='el-icon-info orange ml10'></i>
      </el-popover>
      <template v-if="$store.state.user.vip != 0">
        <span class='ml20'>到期时间：</span>
        <span class='font_success'>{{ $store.state.user.vip_expire_time | formatTime}}</span>
      </template>
    </el-card>
    <el-card class="balance">
      <span >我的余额：</span><span class="balance-monry el-blue">{{ coin }} 元</span>
      <span class="balance-frozenCoin">冻结金额：</span><span class="balance-monry orange">{{ frozenCoin }} 元</span>
      <el-popover
        placement="right"
        title="冻结金额说明"
        width="300"
        trigger="hover"
        >
        <span>冻结金额为近<font class='font_success'>7</font>天的结算金额，每笔结算金额<font class='font_success'>7</font>天后自动解冻为可提现金额。</span>
        <i slot="reference" class='el-icon-info orange ml10'></i>
      </el-popover>
      <!-- <el-button type="primary" @click='queryBalance' v-no-more-click:3000 class='balance-btn'>查询余额</el-button> -->
      <el-button type="primary" @click='withdraw' v-no-more-click:3000 class='balance-btn'>提现</el-button>

      <el-popover
        placement="right"
        title=""
        width="300"
        trigger="hover"
        >
        <span>余额提现到银行卡将收取<font class="font_success">0.6%</font>的手续费</span>
        <i slot="reference" class='el-icon-info orange ml10'></i>
      </el-popover>
    </el-card>

    <el-card class="detail">
      <div slot="header" class="clearfix">

        <el-row :gutter="10">
          <el-col :span="3">
            <span class='detail-title fl'>钱包明细</span>
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="detailTypes"
              multiple
              collapse-tags
              @change='queryTypes'
              placeholder="选择明细类型查询">
              <el-option
                v-for="item in detailTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-date-picker
              v-model="createdTime"
              unlink-panels
              type="daterange"
              range-separator="至"
              format='yyyy-MM-dd'
              value-format='yyyy-MM-dd'
              start-placeholder="开始日期"
              @change='confirmQuery'
              end-placeholder="结束日期">
            </el-date-picker>
          </el-col>
          <el-col :span="5">
            <el-button class='ml10' type="primary" @click='showFrozee'>查看冻结金额明细</el-button>
          </el-col>
          <el-col :span="3">
            <el-button class='fr' :icon='showTable ? "el-icon-arrow-down" : "el-icon-arrow-up"' type='primary' @click="openOrClose">{{showTable ? '收起明细' : '展开明细'}}</el-button>
          </el-col>
        </el-row>
      </div>
      <transition name="draw">
        <el-table
          v-show="showTable"
          :data="detailData"
          ref="table"
          stripe
          border
          :show-header='false'
          v-infinite-scroll="load"
          infinite-scroll-delay='1000'
          infinite-scroll-distance='40'
          infinite-scroll-immediate='false'
          infinite-scroll-disabled="disabled"
          style="width: 100%">
          <el-table-column prop="payMethod" label="支付方式" align="center">
            <template slot-scope="scope">
              {{ scope.row | payMethod }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" align="center">
            <template slot-scope="scope">
              {{ scope.row.type | agentPurseType }}
            </template>
          </el-table-column>
          <el-table-column prop="money" align="center" label="金额">
            <template slot-scope="scope">
              <span :class="scope.row.money >= 0 ? 'font_success' : 'font_danger'">{{ scope.row.money > 0 ? `+${scope.row.money}` : scope.row.money}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" align="center" label="时间">
            <template slot-scope='scope'>
              {{ scope.row.created_at}}
            </template>
          </el-table-column>
        </el-table>
        <!-- <div class='box' v-show="showTable"></div> -->
      </transition>

    </el-card>
    <withdrawDialog ref="withdrawDialog" @refresh='refresh'></withdrawDialog>
    <buyVipDialog ref="buyVipDialog" ></buyVipDialog>
    <frozeeDetail ref="frozeeDetail"/>
  </div>
</template>

<script>
import withdrawDialog from './components/withdrawDialog'
import buyVipDialog from './components/buyVIp-diaglog'
import frozeeDetail from './components/frozeeDetail'
import moment from 'moment'
import QRCode from "qrcode"; // 引入qrcode
import { detailTypeOptions } from './config'
export default {

  data () {

    return {
      vipLogo: '',
      detailData: [],
      createdTime: [],
      paramsByPurse: {
        is_frozee: 2,
        type: '0,1,2,4,7,8,9,10,11,12,13,14,15,16,17'
      },
      coin: '',
      frozenCoin: '',
      qrcodeURL: `http://m.mingyukehui.com/preRegiest?channel_pid=${this.$store.state.user.cryptId}&code=${this.$store.state.user.invitation_code}`,
      pcQrcodeURL: `http://mingyukehui.com/preRegister?channel_pid=${this.$store.state.user.cryptId}&code=${this.$store.state.user.invitation_code}`,
      showTable: true,
      page: 0,
      noMore: false,
      vipLogoClass: '',
      detailTypes: '',
      detailTypeOptions: detailTypeOptions
    }
  },
  components: {
    withdrawDialog,
    buyVipDialog,
    frozeeDetail
  },
  watch: {

    '$store.state.user.vip': {
      handler: function (val) {
        if (val == 0) {
          this.vipLogoClass = 'icon iconfont icon-VIP'
        } else {
          this.vipLogoClass = 'icon iconfont icon-VIP font_red'
        }
      },
      immediate: true,
      // deep: true
    }
  },
  computed: {
    disabled () {
      return this.noMore
    },
  },
  mounted() {
    this.parentId = this.$store.state.user.id;
    this.createQrCode(
      "qrcode",
      this.qrcodeURL
    );
  },
  created () {
    // 默认查询当月明细
    let nowTiem = {
      start_time: `${moment().format("YYYY-MM")}-01`,
      end_time: `${moment().format("YYYY-MM")}-31`,
    }
    // this.paramsByPurse.start_time = `${moment().format("YYYY-MM")}-01`
    // this.paramsByPurse.end_time = `${moment().format("YYYY-MM")}-31`
    this.createdTime[0] = nowTiem.start_time
    this.createdTime[1] = nowTiem.end_time
    this.paramsByPurse.start_time = this.createdTime[0]
    this.paramsByPurse.end_time = this.createdTime[1]
    this.getDetailsData(this.paramsByPurse)
    this.queryBalance()
    // this.getVipLogo()
  },
  methods: {
    queryTypes(value) {
      if (value) {
        this.paramsByPurse.type = value.join(',')
      } else {
        this.paramsByPurse.type = '0,1,2,4,7,8,9,10,11,12,13,14,15,16,17'
      }
      this.getDetailsData(this.paramsByPurse)
      
    },
    debounce(fn, delay, scope) {

      let timer = null;
      // 返回函数对debounce作用域形成闭包
      return function () {
        // setTimeout()中用到函数环境总是window,故需要当前环境的副本；
        let context = scope || this, args = arguments;
        // 如果事件被触发，清除timer并重新开始计时
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
      }
    },
    load() {
      this.page ++
      this.paramsByPurse.page = this.page
      this.getDetailsData(this.paramsByPurse, true)
    },
    showFrozee () {
      this.$refs['frozeeDetail'].show(this.createdTime)
    },
    openOrClose() {
      this.showTable = !this.showTable
    },

    refresh() {
      let nowTiem = {
        start_time: `${moment().format("YYYY-MM")}-01`,
        end_time: `${moment().format("YYYY-MM")}-31`,
      }
      this.getDetailsData(nowTiem)
      this.queryBalance()
    },
    // 购买vip
    buyVip () {
      // this.$refs['buyVipDialog'].show()
      this.$router.replace({
        name: 'payment',
        query: {
          type: 'buyVip',
          vip: btoa('vip1'),
          from: this.$route.path
        }
      })
    },
    // 创建二维码
    createQrCode(refName, payUrl) {
      QRCode.toDataURL(this.$refs[refName], payUrl, {
        width: 120,
        height: 120
      })
        .then(url => {})
        .catch(err => {
          // this.openMessage(0, '生成二维码失败')
        });
    },
    // 获取明细数据
    getDetailsData (pParams, scrollData) {
      let params = {

      }
      if (pParams) {
        params = {...params, ...pParams, ...this.paramsByPurse}
      }

      this.$axios.get('api/drawing/wallet/agent_detail', {
        params: params
      }).then(res => {
        if (res.data.code == 200) {

          if (scrollData) {
            let data = res.data.data
            if (data.length == 0) {
              this.noMore = true
            }
            this.detailData = this.detailData.concat(data)
          } else {
            this.detailData = res.data.data
          }
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 获取余额
    queryBalance () {
      this.$axios.get('api/drawing/wallet').then(res => {
        if (res.data.code == 200) {
          this.coin = res.data.data.coin
          this.frozenCoin = res.data.data.frozenCoin
        } else if (res.data.code == 400) {
          this.$message.error(res.data.message)
        }
      })
    },
    // 发起提现申请
    withdraw() {
      this.queryBalance()
      let data = {
        coin: this.coin,
        frozenCoin: this.frozenCoin
      }
      this.$refs.withdrawDialog.show(data)
    },

    // 时间查询
    confirmQuery () {
      if (this.createdTime) {
        this.paramsByPurse.start_time = this.createdTime[0]
        this.paramsByPurse.end_time = this.createdTime[1]
        this.getDetailsData(this.paramsByPurse)
      } else {
        this.getDetailsData()
      }
    },

    // 复制成功
    onCopy(e){
      this.$message({
        message:'复制成功！',
        type:'success'
      })
    },
    // 复制失败
    onError(e){
      this.$message({
        message:'复制失败！',
        type:'error'
      })
    },
  }
}
</script>

<style lang='less' type='text/css'>
  .myPurse{
    height: auto;
    background: #f5f5f5;
    padding: 20px;
    .balance {
      span {
        font-size: 20px;
      }
      .balance-frozenCoin {
        margin-left: 30px;
      }
      .balance-btn {
        margin-left: 30px;
        span {
          font-size: 14px;
        }
      }
    }
    .detail {
      margin-top: 20px;
      // min-height: 200px;

      .el-card__body {
        overflow-y: auto;
        max-height: 450px;
      }
      .detail-title {
        font-size: 18px;
      }
      .el-date-editor {

        width: 100%;
        min-width: 260px;
      }
      .el-select {
        width: 100%;
      }
      .detail-item {
        font-size:16px;
        margin-bottom: 10px;
        .item-money {
          // float: right;
          margin-left: 200px;
        }
        .item-tiem {
          color: #909399;
          margin-top: 5px;
          float: right;
        }
        .item_type {
          min-width: 200px;
          display: inline-block;
        }
      }

      .Nodata {
        height: 50px;
        position: relative;
        .Nodata-text {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%,-50%);
          font-size: 14px;
        }
      }
    }
    .qrcode {
      margin-top: 20px;
      position: relative;

      &-title {
        font-size: 18px;
      }
      &-btn {
        margin-left: 30px;
      }
      // .url-copy {
      //   position: absolute;
      //   top: 50%;
      //   left: 150px;
      //   transform: translate(0, -50%);
      // }
    }
    .vip_logo {
      width: 22px;
    }

    .font_red {
      color: #d81e06;
    }
  }
  .vip_Introduction {
    margin-top: 10px;
    ul {
      padding-left: 10px;
      li {
        list-style: none;
        span {
          font-size: 14px;
        }
      }
    }
  }
  .draw-enter-active, .draw-leave-active {
    transition: all 0.5s ease-out;
    // animation: against .3s ;
  }
  .draw-enter, .draw-leave-to /* .fade-leave-active below version 2.1.8 */ {
    height: 0 !important;
    // animation: identifier .3s;
  }

  #admin .el-main .myPurse .el-table {
    // height: 450px;
    // overflow-y: auto;
    min-height: 0px;
  }

</style>
